package com.zb.mobile.network.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.zb.constant.NetworkConstant;
import com.zb.entity.*;
import com.zb.enums.SmsCode;
import com.zb.exception.SMSException;
import com.zb.mapper.ZjNetworkEmpRelationMapper;
import com.zb.mobile.NetworkMobileCreateVo;
import com.zb.mobile.network.service.ConNetworkMobileService;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.sms.service.SmsSendMessageService;
import com.zb.util.MobileNetworkSmsUtil;
import com.zb.view.ViewNetworkEmpAccount;
import com.zb.vo.NetworkFieldSelectVo;
import com.zb.vo.NetworkStrategyVo;
import com.zb.vo.NetworkVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author WEN
 * @Date 2023/11/21 0021
 **/
@Service
public class ConNetworkMobileServiceImpl implements ConNetworkMobileService {
    @Resource
    private ZjCustomerService customerService;
    @Resource
    private ZjNetworkFieldService networkFieldService;
    @Resource
    private ZjNetworkEmpRelationService networkEmpRelationService;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ViewNetworkEmpAccountService viewNetworkEmpAccountService;
    @Resource
    private ZjNetworkEmpRelationMapper networkEmpRelationMapper;
    @Resource
    private ZjCustomerInfoService customerInfoService;
    @Resource
    private ZjNetworkStrategyService networkStrategyService;
    @Resource
    private ZjNetworkWithdrawWithFeeEmpRootService networkWithdrawWithFeeEmpRootService;

    // 校验服务商加入企业的邀请码
    @Override
    public void checkNetworkJoinCustomer(AccounLoginInfo loginInfo, String inviteCode) throws SMSException {
        MobileNetworkSmsUtil.checkInviteCode(inviteCode);
    }

    // 根据邀请码获取企业信息
    @Override
    public Map<String, Object> getCustomerInfo(AccounLoginInfo loginInfo, String inviteCode) throws SMSException {
        NetworkInviteCodeVo inviteCodeVo = MobileNetworkSmsUtil.checkInviteCode(inviteCode);

        List<NetworkFieldSelectVo> networkFields = networkFieldService.getNetworkFields(inviteCodeVo.getCustAccId(), true);
        ZjCustomer customer = customerService.getById(inviteCodeVo.getCustAccId());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("networkFields", networkFields);
        resultMap.put("customer", customer.getFullName()); // 企业名称
        return PageUtil.rows(resultMap);
    }

    // 创建服务商
    @Override
    @Transactional
    public void saveNetwork(AccounLoginInfo loginInfo, String inviteCode, NetworkMobileCreateVo networkMobileCreateVo) throws SMSException {
        NetworkInviteCodeVo inviteCodeVo = MobileNetworkSmsUtil.checkInviteCode(inviteCode);

        NetworkVo networkVo = new NetworkVo();
        BeanUtil.copyProperties(networkMobileCreateVo, networkVo);
        networkVo.setCategory(NetworkConstant.CATEGORY_1);
        networkVo.setNetworkTypeId(0L);
        networkVo.setStatus(false);
        networkVo.setAccountId(loginInfo.getId());
        networkVo.setAccountName(loginInfo.getName());

        NetworkStrategyVo strategy = new NetworkStrategyVo();
        strategy.setAutoCheckCancelOrder(false);
        strategy.setAutoCheckEndOrder(false);
        strategy.setEnableUpdateSparePrice(false);
        strategy.setAutoSureReceiveOrder(true);
        strategy.setWithdrawHandlingFeeStrategy(1);
        strategy.setHandingFeeProportion(new BigDecimal("0.0"));
        strategy.setHandingFeeFixedOrder(new BigDecimal("0.0"));
        strategy.setAllowWithdrawal(true);
        List<Long> empRoots = new ArrayList<>();
        empRoots.add(-1L);
        strategy.setSelectFeeEmpRootVos(empRoots);
        strategy.setAllowSelectFee(true);
        strategy.setSelectFeeEmpRootVos(empRoots);
        networkVo.setStrategy(strategy);

        loginInfo.setCustAccId(inviteCodeVo.getCustAccId());
        networkService.save(loginInfo, networkVo);
    }

    // 检查手机号是否加入服务商
    @Override
    public void checkPhoneJoinNetwork(AccounLoginInfo loginInfo, String phone) throws SMSException {
        ViewNetworkEmpAccount networkEmpAccount = viewNetworkEmpAccountService.getByPhone(phone);
        if (null != networkEmpAccount) {
            ZjNetworkEmpRelation empRelation = networkEmpRelationMapper.getByNetworkIdAndNetworkEmpId(loginInfo.getNetworkId(), networkEmpAccount.getId());
            Assert.isTrue(null == empRelation, "该手机号已加入团队");
        }
        // 获取邀请码
        String inviteCode = SmsVerificCodeService.generatorJoinNetworkInviteCode(loginInfo.getCustAccId(), loginInfo.getNetworkId(), phone);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("network", networkService.getNameById(loginInfo.getNetworkId()));
        paramMap.put("code", inviteCode);
        SmsSendMessageService.sendNoticeSms(true, loginInfo, SmsCode.ENGINEER_INVITE_CODE.getCode(), phone, "", paramMap);
    }

    // 获取提现权限
    @Override
    public Object getWithdrawRoot(AccounLoginInfo loginInfo) {
        // 查询是否允许提现
        ZjNetworkStrategy networkStrategy = networkStrategyService.getById(loginInfo.getNetworkId());
        if (null != networkStrategy && !networkStrategy.getAllowWithdrawal()) {
            return false;
        }
        ZjNetworkEmpRelation empRelation = networkEmpRelationService.getNetworkEmpIdAndNetworkId(loginInfo.getNetworkEmpId(), loginInfo.getNetworkId());
        if (null != empRelation && (empRelation.getManager() || empRelation.getSuperManager())) {
            QueryWrapper<ZjNetworkWithdrawWithFeeEmpRoot> withFeeEmpRootQueryWrapper = new QueryWrapper<>();
            withFeeEmpRootQueryWrapper.select("network_emp_id")
                    .eq("type", 1)
                    .eq("network_id", loginInfo.getNetworkId())
                    .in("network_emp_id", "-1", loginInfo.getNetworkEmpId())
                    .last("limit 1");
            return networkWithdrawWithFeeEmpRootService.count(withFeeEmpRootQueryWrapper) > 0;
        }
        QueryWrapper<ZjNetworkWithdrawWithFeeEmpRoot> withFeeEmpRootQueryWrapper = new QueryWrapper<>();
        withFeeEmpRootQueryWrapper.select("network_emp_id")
                .eq("type", 1)
                .eq("network_id", loginInfo.getNetworkId())
                .eq("network_emp_id", loginInfo.getNetworkEmpId())
                .last("limit 1");
        return networkWithdrawWithFeeEmpRootService.count(withFeeEmpRootQueryWrapper) > 0;
    }

    // 获取查询费用权限
    @Override
    public Object getSelectFeeRoot(AccounLoginInfo loginInfo) {
        // 查询是否允许提现
        ZjNetworkStrategy networkStrategy = networkStrategyService.getById(loginInfo.getNetworkId());
        if (null != networkStrategy && !networkStrategy.getAllowSelectFee()) {
            return false;
        }
        ZjNetworkEmpRelation empRelation = networkEmpRelationService.getNetworkEmpIdAndNetworkId(loginInfo.getNetworkEmpId(), loginInfo.getNetworkId());
        if (null != empRelation&& (empRelation.getManager() || empRelation.getSuperManager())) {
            QueryWrapper<ZjNetworkWithdrawWithFeeEmpRoot> withFeeEmpRootQueryWrapper = new QueryWrapper<>();
            withFeeEmpRootQueryWrapper.select("network_emp_id")
                    .eq("type", 2)
                    .eq("network_id", loginInfo.getNetworkId())
                    .in("network_emp_id", "-1", loginInfo.getNetworkEmpId())
                    .last("limit 1");
            return networkWithdrawWithFeeEmpRootService.count(withFeeEmpRootQueryWrapper) > 0;
        }
        QueryWrapper<ZjNetworkWithdrawWithFeeEmpRoot> withFeeEmpRootQueryWrapper = new QueryWrapper<>();
        withFeeEmpRootQueryWrapper.select("network_emp_id")
                .eq("type", 2)
                .eq("network_id", loginInfo.getNetworkId())
                .eq("network_emp_id", loginInfo.getNetworkEmpId())
                .last("limit 1");
        return networkWithdrawWithFeeEmpRootService.count(withFeeEmpRootQueryWrapper) > 0;
    }

    // 获取是否允许超管代工程师提现
    @Override
    public Object getIsAllowManagerHelpWithdrawStrategy(AccounLoginInfo loginInfo) {
        ZjNetworkEmpRelation empRelation = networkEmpRelationService.getNetworkEmpIdAndNetworkId(loginInfo.getNetworkEmpId(), loginInfo.getNetworkId());
        if (null != empRelation && (empRelation.getManager() || empRelation.getSuperManager())) {
            ZjNetworkStrategy strategy = networkStrategyService.getById(loginInfo.getNetworkId());
            return strategy.getAllowManagerHelpWithdraw();
        }
        return false;
    }
}
